#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// 1.验证子进程退出，给父进程发送SIGCHLD
// 2.我们可以基于信号进行子进程回收

void handler(int signo)
{
    std::cout << "father pid: " << getpid() << ", get a signal: " << signo << std::endl;
    while (true)
    {
        pid_t rid = ::waitpid(-1, nullptr, WNOHANG); //非阻塞轮询
        // 若 rid==0: 该子进程没有退出
        // 若 rid==-1: 不存在子进程
        if (rid > 0)
        {
            std::cout << "child exit and recycle success, child pid: " << rid << std::endl;
        }
        else if (rid == 0)
        {
            std::cout << "退出的子进程, 都被回收" << std::endl;
            break;
        }
        else
        {
            std::cout << "wait error" << std::endl;
            break;
        }
    }
}

int main()
{
    signal(SIGCHLD, handler);

    for (int i = 0; i < 10; i++)
    {
        if (fork() == 0)
        {
            // 子进程
            sleep(5);
            if (i < 5)
            {
                std::cout << "子进程退出" << std::endl;
                exit(0);
            }
            else
            {
                std::cout << "子进程永不退出" << std::endl;
                while (true)
                {
                    sleep(1);
                }
            }
        }
    }

    while (true)
    {
        sleep(1);
    }

    return 0;
}